import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
	{
	  path: '/',
	  name: 'Home',
	  component: () => import('../views/home'),
		meta: {
			keepalive: true
		}
	},
	{
	  path: '/register',
	  name: 'Register',
	  component: () => import('../views/register.vue')
	},
	{
	  path: '/login',
	  name: 'Login',
	  component: () => import('../views/login.vue')
	},
	{
	  path: '/userinfo',
	  name: 'UserInfo',
	  component: () => import('../views/userinfo')
	},
	{
	  path: '/edit',
	  name: 'Edit',
	  component: () => import('../views/edit')
	},
	{
	  path: '/detail',
	  name: 'Detail',
	  component: () => import('../views/detail')
	},
	{
	  path: '/editcategory',
	  name: 'Editcategory',
	  component: () => import('../views/editcategory')
	}
]

const router = new VueRouter({
  routes,
	mode: 'history'
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => { 
	// to => 将要访问的路径
	// from => 从哪个路径跳转而来
	// next => 是个函数，表示放行
	// next()=>放行   next('/login')=>	强制跳转

	if (to.path === '/login' || to.path === '/' || to.path === '/detail' || to.path === '/register') {
		return next()
	}

	// 获取token 和 id
	const tokenStr = window.localStorage.getItem('token')
	const idStr = window.localStorage.getItem('id')
	
	if (!tokenStr || !idStr) {
		Vue.prototype.$toast.fail('登录过期，请重新登录！')
		return next('/login')
	} else {
		next()
	}
})


export default router
